package com.sunrise.financeiro.repositorio;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.sunrise.financeiro.repositorio.iface.BoletoDao;
import com.sunrise.generico.acesso.DaoService;
import com.sunrise.generico.entidade.Boleto;
import com.sunrise.generico.visao.Filtro;

@Repository
public class BoletoDaoImpl extends DaoService<Boleto> implements BoletoDao {

	public List<Boleto> listarOrdenado() {
		List<Boleto> list = listar(Boleto.class);
		Collections.sort(list, new Comparator<Boleto>() {

			@Override
			public int compare(Boleto o1, Boleto o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public List<Boleto> search(Boleto ex) {
		List<Boleto> list = searchByExample(Boleto.class, ex);
		Collections.sort(list, new Comparator<Boleto>() {

			@Override
			public int compare(Boleto o1, Boleto o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public Boleto getById(Long id) {
		return getById(id, Boleto.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Boleto> buscarPorFiltros(Filtro filtro) {
		Criteria crit = getSession().createCriteria(Boleto.class);

		if (filtro.getNome() != null) {
			crit.add(Restrictions.ilike("nome", filtro.getNome(), MatchMode.ANYWHERE));
		}

		crit.createAlias("cedente", "cd");
		crit.createAlias("cd.usuarios", "usuario");
		crit.add(Restrictions.eq("usuario.id", filtro.getIdUsuarioLogado()));

		crit.addOrder(Order.asc("nome"));
		return crit.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Boleto> listarPorNome(String nome) {
		Criteria crit = getSession().createCriteria(Boleto.class);
		crit.add(Restrictions.ilike("nome", nome, MatchMode.ANYWHERE));
		return crit.list();
	}

	@Override
	public Boleto buscarPorNome(String nome) {
		return null;
	}

	@Override
	public long buscarUltimoNossoNumero() {
		Criteria crit = getSession().createCriteria(Boleto.class).setProjection(Projections.max("nossoNumero"));
		Object o = crit.uniqueResult();
		if(o == null){
			return 1;
		}else{
			return (Long) o;
		}
	}

}
